﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Linq.Expressions;

namespace ANTLR01
{
    public class SimpleUnaryOperationBinder : UnaryOperationBinder
    {
        public SimpleUnaryOperationBinder(ExpressionType expressionType)
            : base(expressionType)
        {
        }

        public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
        {
            if (!target.HasValue)
            {
                return Defer(target);
            }
            
            var restrictions = target.Restrictions.Merge(BindingRestrictions.GetTypeRestriction(target.Expression, target.LimitType));
            
            return new DynamicMetaObject(
                ExpressionEx.EnsureObjectResult(Expression.MakeUnary(
                    Operation,
                    Expression.Convert(target.Expression, target.LimitType),
                    target.LimitType
                )),
                restrictions
            );
        }
    }
}